package com.dk.service.content;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.dk.data.RedisContent;
import com.dk.mapper.content.TbContentMapper;
import com.dk.pojo.content.TbContent;
import com.dk.pojo.content.TbContentExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Service
@Component
public class ContentServiceImpl implements ContentService {

    @Resource
    private TbContentMapper contentMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<TbContent> listContentByCategoryId(Long categoryId) {
//        ValueOperations ops = redisTemplate.opsForValue();
//        if (redisTemplate.hasKey(RedisContent.CONTENT_WEB_KEY + categoryId)) {
//            String string = (String) ops.get(RedisContent.CONTENT_WEB_KEY + categoryId);
//            List<TbContent> contents = JSONObject.parseArray(string, TbContent.class);
//            return contents;
//        } else {

            TbContentExample contentExample = new TbContentExample();
            TbContentExample.Criteria criteria = contentExample.createCriteria();
            criteria.andCategoryIdEqualTo(categoryId);
            List<TbContent> contents = contentMapper.selectByExample(contentExample);
            String string = JSONObject.toJSONString(contents);
//            ops.set(RedisContent.CONTENT_WEB_KEY + categoryId,string);
            return contents;
//        }
    }

    /**
     * 修改
     * @param content
     * @return
     */
    @Override
    public int updateContent(TbContent content) {
//        redisTemplate.delete(RedisContent.CONTENT_WEB_KEY);
        return contentMapper.updateByPrimaryKeySelective(content);
    }

    /**
     * 通过id获取广告
     * @param id
     * @return
     */
    @Override
    public TbContent contentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    /**
     * 保存
     * @param content
     * @return
     */
    @Override
    public int saveContent(TbContent content) {
//        redisTemplate.delete(RedisContent.CONTENT_WEB_KEY);
        return contentMapper.insertSelective(content);
    }

    /**
     * 获取广告列表
     * @return
     */
    @Override
    public List<TbContent> listContent() {
        return contentMapper.selectByExample(null);
    }
}
